<?php

namespace catchAdmin\model;

use catcher\exceptions\AlertErrorException;

class UserCompany extends ModelApp
{

    protected $append = [
        'audit_time_show',
        'company_status_name',
        'company_type_name',
        'company_license_show',
        'sh',
    ];

    protected $type = [
        'dian_id'    => 'array',
        'ji_tuan_id' => 'array',
        'wai_mao_id' => 'array',

        'company_license' => 'array',
        'zi_zhi'          => 'array',
        'zheng_shu_img'   => 'array',
        'zi_zhi_more_img' => 'array',
    ];


    ############################ 关系 start ###############################

    public function wechatUser()
    {
        return $this
            ->hasOne(WechatUser::class, 'id', 'wechat_user_id')
            ->bind([
                'wechat_user_phone' => 'phone',
            ]);
    }

    ############################ 关系 end ###############################
    ############################ Attr start ###############################

    public function getDianList()
    {
        return [
            0 => '无',
            1 => '国家电网',
            2 => '南方电网',
            3 => '蒙西电网',
        ];
    }


    public function getJiTuanList()
    {
        return [
            0  => '无',
            1  => '国家能源投资集团',
            2  => '中国华能集团',
            3  => '中国华电集团',
            4  => '中国大唐集团',
            5  => '国家电力投资集团',
            6  => '国投电力',
            7  => '中广核',
            8  => '三峡集团',
            9  => '华润电力',
            10 => '中节能',
            11 => '中核集团',
        ];
    }


    public function getWaiMaoList()
    {
        return [
            1 => '已有外贸订单',
            2 => '正在拓展暂无订单',
            3 => '计划拓展没有头绪',
            4 => '没有计划',
        ];
    }


    /**
     * sh
     */
    public function getShAttr($value, $data)
    {
        return $this->getOrigin()['company_status'] == 3 ? 0 : 1;
    }


    /**
     * audit_time_show
     */
    public function getAuditTimeShowAttr()
    {
        if (empty($this->getOrigin('audit_time'))) {
            return '';
        }

        return date('Y-m-d H:i:s', $this->getOrigin('audit_time'));
    }


    /**
     * city_code
     */
    public function getCityCodeAttr()
    {
        return [
            substr($this->getOrigin('city_code'), 0, 2) . "0000",
            substr($this->getOrigin('city_code'), 0, 4) . "00",
            $this->getOrigin('city_code'),
        ];
    }


    /**
     * company_status_name_list
     */
    public function getCompanyStatusNameList()
    {
        return [
            2 => '审核中',
            3 => '审核通过',
            4 => '审核未通过',
        ];
    }


    /**
     * company_status_name
     */
    public function getCompanyStatusNameAttr()
    {
        return $this->getCompanyStatusNameList()[$this->getOrigin('company_status')] ?? '';
    }


    /**
     * company_type_name_list
     */
    public function getCompanyTypeNameList()
    {
        return [
            1 => '居间人',
            2 => '工程公司',
            3 => '物资工厂',
            4 => '设计公司',
            5 => '监理公司',
            6 => '劳务公司',
            7 => '贸易公司',
            8 => '行业协会',
        ];
    }


    /**
     * company_type_name
     */
    public function getCompanyTypeNameAttr()
    {
        return $this->getCompanyTypeNameList()[$this->getOrigin('company_type')] ?? '';
    }


    /**
     * company_license_show
     */
    public function getCompanylicenseShowAttr()
    {
        if (substr($this->getOrigin('company_license'), 0, 4) == 'http') {
            return $this->getOrigin('company_license');
        }

        return request()->domain() . $this->getOrigin('company_license') ?? '';
    }


    ############################ Attr end ###############################
    ############################ search start ###############################

    public function searchCompanyNameAttr($query, $value, $data)
    {
        $query->where('company_name', 'like', '%' . $value . '%');
    }


    public function searchPersonMobileAttr($query, $value, $data)
    {
        $query->where('person_mobile', 'like', '%' . $value . '%');
    }


    public function searchCompanyTypeAttr($query, $value, $data)
    {
        $query->where('company_type', $value);
    }


    public function searchCompanyStatusAttr($query, $value, $data)
    {
        $query->where('company_status', $value);
    }


    public function searchLinkmanMobileAttr($query, $value, $data)
    {
        $query->where('linkman_mobile', 'like', '%' . $value . '%');
    }


    ############################ search end ###############################

    public function saveDataApp($param)
    {
        $msg_arr = [
            'wechat_user_id'      => $this->getLoginId(),
            'company_status'      => 2,
            'company_status_note' => '',
            'apply_time'          => time(),
            'audit_time'          => time(),
            'status_no'           => date('Ymd_') . rand(100, 999),

            'parent_id' => $param['parent_id'] ?? 0,

            'company_type'    => $param['company_type'] ?? 0,
            'company_name'    => $param['company_name'] ?? '',
            'company_license' => $param['company_license'] ?? '',
            'team_name'       => $param['team_name'] ?? '',

            'city_code'    => $param['city_code'] ?? [],
            'city_address' => $param['city_address'] ?? '',
            'city_long'    => $param['city_long'] ?? 0,
            'city_lat'     => $param['city_lat'] ?? 0,

            'main_customer'   => $param['main_customer'] ?? '',
            'main_ye_wu'      => $param['main_ye_wu'] ?? '',
            'zi_zhi'          => $param['zi_zhi'] ?? [],
            'zheng_shu_img'   => $param['zheng_shu_img'] ?? [],
            'zi_zhi_more_img' => $param['zi_zhi_more_img'] ?? [],

            'make_goods'       => $param['make_goods'] ?? '',
            'sale_goods'       => $param['sale_goods'] ?? '',
            'zhu_guan_company' => $param['zhu_guan_company'] ?? '',
            'user_num'         => $param['user_num'] ?? '',

            'dian_id'    => $param['dian_id'] ?? [],
            'ji_tuan_id' => $param['ji_tuan_id'] ?? [],
            'wai_mao_id' => $param['wai_mao_id'] ?? [],

            'person_realname' => $param['person_realname'] ?? '',
            'person_duty'     => $param['person_duty'] ?? '',
            'person_mobile'   => $param['person_mobile'] ?? '',

            'linkman_realname' => $param['linkman_realname'] ?? '',
            'linkman_duty'     => $param['linkman_duty'] ?? '',
            'linkman_mobile'   => $param['linkman_mobile'] ?? '',
            'linkman_email'    => $param['linkman_email'] ?? '',
        ];

        // 城市名
        if (!empty($param['city_code']) && is_array($param['city_code'])) {
            $name_arr = [];
            foreach ($param['city_code'] as $key => $value) {
                $name_arr[] = (new Area())
                    ->where('code', $value)
                    ->value('name');
            }

            $msg_arr['city_code'] = end($param['city_code']);
            $msg_arr['city_name'] = implode('', $name_arr);
        }

        // 上级
        if (!empty($param['parent_id'])) {
            $parent_msg = (new WechatUser())
                ->where('id', $param['parent_id'])
                ->find();
            if (empty($parent_msg)) {
                throw new AlertErrorException('推广人不存在');
            }

            $msg_arr['parent_name'] = $parent_msg['name'];
            $msg_arr['parent_share_code'] = $parent_msg['share_code'];
        }

        if (!empty($param['register_date'])) {
            $msg_arr['register_date'] = $param['register_date'];
        }
        if (!empty($param['run_date'])) {
            $msg_arr['run_date'] = $param['run_date'];
        }

        if (!empty($param['dian_id'])) {
            $dian_name = [];
            foreach ($param['dian_id'] as $key => $value) {
                $dian_name[] = $this->getDianList()[$value] ?? '';
            }

            $param['dian_name'] = implode('，', $dian_name);
        }
        if (!empty($param['ji_tuan_id'])) {
            $ji_tuan_name = [];
            foreach ($param['ji_tuan_id'] as $key => $value) {
                $ji_tuan_name[] = $this->getJiTuanList()[$value] ?? '';
            }

            $param['ji_tuan_name'] = implode('，', $ji_tuan_name);
        }
        if (!empty($param['wai_mao_id'])) {
            $wai_mao_name = [];
            foreach ($param['wai_mao_id'] as $key => $value) {
                $wai_mao_name[] = $this->getWaiMaoList()[$value] ?? '';
            }

            $param['wai_mao_name'] = implode('，', $wai_mao_name);
        }

        $msg = $this
            ->where('wechat_user_id', $msg_arr['wechat_user_id'])
            ->find();
        if (!empty($msg)) {
            if ($msg['company_status'] == 3) {
                throw new AlertErrorException('已通过的审核，不允许修改');
            }
            if ($msg['company_status'] == 2) {
                throw new AlertErrorException('正在审核中，不允许修改');
            }

            $msg_arr['id'] = $msg['id'];
        }

        return parent::saveDataCC($msg_arr); // TODO: Change the autogenerated stub
    }

}
